package com.java.demo.model;

import java.util.Observable;
import java.util.Observer;

/**
 * @auther zhangwj
 * @date 2021/1/4 上午11:36
 */
public class ObserverPatternJdk {

    public static void main(String[] args) {
        WeatherData1 weatherData1 = new WeatherData1();
        ThirdPartyDisplay1 thirdPartyDisplay = new ThirdPartyDisplay1(weatherData1);
        weatherData1.setMeasurements(10, 20, 30);
        thirdPartyDisplay.display(thirdPartyDisplay.obj);
    }
}

class WeatherData1 extends Observable {

    WeatherData1() {
    }

    public void measurementsChanged() {
        setChanged();
        notifyObservers(this.toString());
    }

    public void setMeasurements(int temperature, int humidity, int pressure) {
        this.temperature = temperature;
        this.humidity = humidity;
        this.pressure = pressure;
        measurementsChanged();
    }

    // 温度
    private int temperature;

    // 湿度
    private int humidity;

    // 压强
    private int pressure;

    public int getTemperature() {
        return temperature;
    }

    public void setTemperature(int temperature) {
        this.temperature = temperature;
    }

    public int getHumidity() {
        return humidity;
    }

    public void setHumidity(int humidity) {
        this.humidity = humidity;
    }

    public int getPressure() {
        return pressure;
    }

    public void setPressure(int pressure) {
        this.pressure = pressure;
    }

    @Override
    public String toString() {
        return "WeatherData1{" +
                "temperature=" + temperature +
                ", humidity=" + humidity +
                ", pressure=" + pressure +
                '}';
    }
}

interface DisplayElement1 {

    void display(Object arg);
}

// 第三方显示
class ThirdPartyDisplay1 implements Observer, DisplayElement1 {

    Observable weatherData;

    Object obj;

    ThirdPartyDisplay1(Observable weatherData) {
        this.weatherData = weatherData;
        weatherData.addObserver(this);
    }

    // 现实基于观测值的其他内容
    @Override
    public void display(Object arg) {
        System.out.println(arg);
    }

    @Override
    public void update(Observable obs, Object arg) {
        this.obj = arg;
    }
}